let systemPersonModel = require('../model/systemPersonModel')
let companyModel = require('../model/companyModel')
let mongoose = require('mongoose')
let jwt = require('jsonwebtoken')



let login = async (request, response) => {
  const {email, password} = request.body
  const emailReg = /^[a-zA-Z0-9_]{2,16}@[a-zA-Z0-9]{2,16}\.com$/
  const passwordReg = /^[a-zA-Z0-9_#]{6,16}$/
  const errMsg = {}
  //使用正则进行校验
  if (!emailReg.test(email)) {
    errMsg.emailErr = '邮箱输入不合法！要求邮箱用户名2-16位不包含特殊字符，邮箱主机名2-16位'
  }
  if (!passwordReg.test(password)) {
    errMsg.passwordErr = '密码输入不合法，密码应为6-16位字符不包含特殊字符'
  }
  if (JSON.stringify(errMsg) !== '{}') {
    response.status(200).send({
      data: null,
      meta: {
        msg: errMsg,
        code: 0
      }
    })
    return
  }

  try {
    let findResult = await systemPersonModel.findOne({email: email, password: password})
    if (findResult) {
      let personName = findResult.personName
      errMsg.successErr = '登录成功'
      // 登录成功生成token返回给客户端
      // 第一个参数是组,第二个参数是密匙自己谁便定义
      let token = jwt.sign({personName}, 'iamtoken')
      response.status(200).send({
        data: {
          personName: personName,
          token: token
        },
        meta: {
          msg: errMsg,
          code: 1
        }
      })


      // response.status(200).send({errMsg})
    } else {
      errMsg.loginErr = '登录失败，邮箱或密码输入错误！'
      response.status(200).send({
          data: null,
          meta: {
            msg: errMsg,
            // 1表示成功
            // 0表示失败
            code: 0
          }
        }
      )
    }
  } catch (err) {
    errMsg.networkErr = '数据库连接不稳定'
    response.status(200).send({
      data: null,
      meta: {
        msg: errMsg,
        // 1表示成功
        // 0表示失败
        code: 0
      }
    })
  }
}
let register = async (request, response) => {
  let {companyId, companyName} = request.body
  // 数据库错误会在这里捕捉到,而不是try
  // 没查到data返回null;数据库错误data返回undefined
  // 数据库无错误,查没查到err都为null;数据库有错误err有值
  // 避免崩溃 try一下
  let companyId2
  try {
    companyId2 = mongoose.Types.ObjectId(companyId)
  } catch (e) {
    response.status(500).send({
      data: null,
      meta: {
        msg: "公司校验码不存在"
      }
    })
    // return之后后面不会执行
    return
  }

  companyModel.findOne({_id: companyId2}, (err, data) => {
      // 数据库无错误
      if (!err) {
        if (data === null) {
          response.status(500).send({
            data: null,
            meta: {
              msg: "公司校验码不存在"
            }
          })
        }
        // 找到了
        else if (data.companyname !== companyName) {
          response.status(500).send({
            data: null,
            meta: {
              msg: "公司校验码与公司名称不对应"
            }
          })
        }
        // 成功了
        else {
          testInsertUserData(request, response)
        }
      } else {
        // 数据库有错误
        response.status(500).send({
          data: null,
          meta: {
            msg: "后端服务错误"
          }
        })
      }
    }
  )
}
// 定义向数据库插入数据的函数
let testInsertUserData = (request, response) => {
  let {email, personName, companyId, companyName, password, personRoleId, personDepartmentId} = request.body
  systemPersonModel.findOne({email: email}, (err, data) => {
    // 数据库无错误
    if (!err) {
      if (data === null) {
        systemPersonModel.create({email, personName, companyId, companyName, password, personRoleId, personDepartmentId}, (err2, data2) => {
          if (err2) {
            response.status(500).send({
              data: null,
              meta: {
                msg: "注册失败"
              }
            })
          } else {
            response.status(200).send({
              data: null,
              meta: {
                msg: "注册成功"
              }
            })
          }
        })
      } else {
        response.status(500).send({
          data: null,
          meta: {
            msg: "此邮箱已经注册过"
          }
        })
      }

    } else {
      response.status(500).send({
        data: null,
        meta: {
          msg: "后端服务错误"
        }
      })
    }
  })
}
let testRouter = async (req, res, next) => {
  if (req.url === '/login' || req.url === '/register') {
    next()
    return
  }
  const token = String(req.headers.authorization)
  const personName = jwt.decode(token, 'iamtoken')
  if (token == 'undefined' || personName == null) {
    res.status(400).send({
      data: null,
      meta: {
        msg: "token无效",
        status: 400
      }
    })
    return
  }
  // 有token直接放行
  next()
}

let loginAndRegisHanlde = {}
loginAndRegisHanlde.login = login
loginAndRegisHanlde.register = register
loginAndRegisHanlde.testRouter = testRouter



module.exports = loginAndRegisHanlde